﻿using Prism.Regions;
using SmartParkingClient.IBLL;
using SmartParkingClient.SystemModule.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartParkingClient.SystemModule.ViewModels
{
    public class TreeMenuViewModel
    {
        // 需要多数据库的单列模式的数据转换成树状结构     递归
        public ObservableCollection<MenuItemModel> Menus { get; set; } = new ObservableCollection<MenuItemModel>();

        List<Entity.MenuEntity> origMenus { get; set; }

        private IRegionManager _regionManager = null;

        public TreeMenuViewModel(IMenuBLL menuBLL, IRegionManager regionManager)
        {
            _regionManager = regionManager;
            // 需要初始化的进候进行菜单数据的获取填充
            // 通过Api接口

            Task.Run(async () =>
            {
                origMenus = await menuBLL.GetMenus(0);

                this.FillMenus(Menus, 0);
            });
        }


        ///递归
        ///
        private void FillMenus(ObservableCollection<MenuItemModel> menus, int parentId)
        {
            // 根据菜单ID查找对应的直接子节点，第一层的菜单，父节点为0
            var sub = origMenus.Where(m => m.parentId == parentId).OrderBy(o => o.index);

            if (sub.Count() > 0)
            {
                foreach (var item in sub)
                {
                    //MenuItemModel mm = new MenuItemModel(_regionManager)
                    MenuItemModel mm = new MenuItemModel(_regionManager)
                    {
                        MenuHeader = item.menuHeader,
                        MenuIcon = item.menuIcon,
                        TargetView = item.targetView
                    };
                    menus.Add(mm);

                    FillMenus(mm.Children = new ObservableCollection<MenuItemModel>(), item.menuId);
                }
            }
        }
    }
}
